import {
  users
} from "~/tools/users.js"
import {
  shops
} from "~/tools/shops.js"
import {
  ds
} from "~/tools/data.js"
import {
  ui
} from "~/tools/ui"
import {
  pages
} from "~/tools/pages"
Page({
  data: {
    id: '',
    user: {},
    shops: [],
    shopChecked: {}
  },
  onLoad(options) {
    this.setData({
      id: options.id
    })
    this.loadUser()
  },
  loadUser() {
    const that = this
    users.getUserById(this.data.id)
      .then(user => {
        that.setData({
          user
        })
        that.loadShops()
      })
  },
  loadShops() {
    const {
      user
    } = this.data
    const shopList = shops.getShopList(),
      shopChecked = {}
    this.setData({
      shops: shopList
    })
    shopList.forEach(s => {
      shopChecked[s.id] = (user.shops?.includes(`${s.id}`))
    })
    this.setData({
      shopChecked
    })
  },
  roleChange(e) {
    this.setData({
      'user.role': e.detail.value
    })
  },
  shopChange(e) {
    this.setData({
      'user.shops': e.detail.value
    })
  },
  backTap() {
    wx.navigateBack()
  },
  saveTap() {
    const {
      user
    } = this.data
    ui.loading()
    ds.cloudUpdate('users', user._id, {
      'role': user.role,
      'shops': user.shops
    }, res => {
      ui.loading(false)
      const success = res.result.errMsg.endsWith(":ok")
      ui.toast(success)
      if (success) pages.back(pre => pre.init())
    })
  }
})